package lib

import (
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/xormplus/core"
	"github.com/xormplus/xorm"

	"gitee.com/krio/grpc-go-server/dao/model/region"
	"gitee.com/krio/grpc-go-server/dao/model/user"
	"gitee.com/krio/helper/logger"
)

var (
	X *xorm.Engine
)

// InitXormMysql 初始化数据库mysql
func InitXormMysql() *xorm.Engine {
	var (
		url   = C.Mysql.URL
		fPath = C.Mysql.FPath
		err   error
	)
	X, err = xorm.NewEngine("mysql", url)
	if err != nil {
		logger.Errorf("mysql connect failed, err: %+v", err)
	}
	maxIdle := C.Mysql.MaxIdle
	X.SetConnMaxLifetime(2 * time.Hour)
	X.SetMaxOpenConns(200)
	X.SetMaxIdleConns(maxIdle)
	X.SetTableMapper(core.NewPrefixMapper(core.GonicMapper{}, ""))
	X.SetColumnMapper(core.GonicMapper{})
	// 注册sql模板文件
	err = X.RegisterSqlTemplate(xorm.Pongo2(fPath+"/stpl", ".stpl"))
	if err != nil {
		logger.Errorf("register sql template failed, err: %+v", err)
	}

	// if err = X.Ping(); err != nil {
	// 	logger.Errorf("mysql ping failed, err:", err)
	// }
	// 自动注册表
	err = X.Sync2(
		new(user.UserInfo),
		new(user.UserLogin),
		new(user.UserEducation),
		new(region.Country),
		new(region.Region),
	)
	if err != nil {
		logger.Fatalf("mysql sync failed, err: %+v", err)
	}
	X.ShowSQL(C.Mysql.ShowSQL)

	return X
}
